package com.huatai.bpmn.commom.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class SecurityUtil {

	private Logger logger = LoggerFactory.getLogger(SecurityUtil.class);

	private static InMemoryUserDetailsManager inMemoryUserDetailsManager;

	//查询实例
	public static InMemoryUserDetailsManager findInstance(){
		if(inMemoryUserDetailsManager==null){
			inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
		}
		return inMemoryUserDetailsManager;
	}

	public void createUser(String userName) {
		inMemoryUserDetailsManager = findInstance();
		if(inMemoryUserDetailsManager.userExists(userName)) {
			inMemoryUserDetailsManager.deleteUser(userName);
		}
		List<SimpleGrantedAuthority> roles = new ArrayList<SimpleGrantedAuthority>(){{
			add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER"));
			add(new SimpleGrantedAuthority("GROUP_activitiTeam"));
		}};
		inMemoryUserDetailsManager.createUser(new User(userName, passwordEncoder().encode("password"),roles));
	}

	public void logInAs(String username) {
		createUser(username);
		UserDetails user = findInstance().loadUserByUsername(username);
		if (user == null) {
			throw new IllegalStateException("User " + username + " doesn't exist, please provide a valid user");
		}
		logger.info("> Logged in as: " + username);
		SecurityContextHolder.setContext(new SecurityContextImpl(new Authentication() {
			@Override
			public Collection<? extends GrantedAuthority> getAuthorities() {
				return user.getAuthorities();
			}

			@Override
			public Object getCredentials() {
				return user.getPassword();
			}

			@Override
			public Object getDetails() {
				return user;
			}

			@Override
			public Object getPrincipal() {
				return user;
			}

			@Override
			public boolean isAuthenticated() {
				return true;
			}

			@Override
			public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

			}

			@Override
			public String getName() {
				return user.getUsername();
			}
		}));
		org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);
	}

	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}
